package com.xq.jltx.frescosimple.fragment;

import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.xq.jltx.frescosimple.R;
import com.xq.jltx.frescosimple.adapters.FrescoListViewAdapter;
import com.xq.jltx.frescosimple.adapters.ImageListAdapter;
import com.xq.jltx.frescosimple.config.Constants;
import com.xq.jltx.frescosimple.config.imagepipeline.ConfigConstants;
import com.xq.jltx.frescosimple.config.imagepipeline.ImagePipelineConfigFactory;
import com.xq.jltx.frescosimple.display.PerfListener;
import com.xq.jltx.frescosimple.utils.FrescoUtils;
import com.xq.jltx.frescosimple.utils.XqLog;

import java.io.File;

/**
 * @author jltxseo
 *         Created by junlintianxia on 2016年02月02日.
 */

public class ImageListViewFragment extends BackHandledFragment{

    private static final String ARG_PARAM1 = "param1";
    private static final String ARG_PARAM2 = "param2";
    private ListView listView;

    private int mCurrentAdapterIndex;
    private ImageListAdapter mCurrentAdapter;
    private String[] imgList;

    private PerfListener mPerfListener;
    public ImageListViewFragment() {
    }

    /**
     * 通过这个静态工厂方法去传递参数
     * @param params
     * @return
     */
    public static ImageListViewFragment newInstance(String[] params,int currentIndex){
        ImageListViewFragment imageListViewFragment = new ImageListViewFragment();
        Bundle args = new Bundle();
        args.putCharSequenceArray(ARG_PARAM1,params);
        args.putInt(ARG_PARAM2,currentIndex);
        imageListViewFragment.setArguments(args);
        return imageListViewFragment;
    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        if(getArguments() != null){
            imgList = (String[])getArguments().getCharSequenceArray(ARG_PARAM1);
            mCurrentAdapterIndex = getArguments().getInt(ARG_PARAM2);
        }
        super.onCreate(savedInstanceState);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_listview,null,false);
        if(view instanceof ListView){
            listView = (ListView)view;
        }
        return view;
    }


    @Override
    public void onViewCreated(View view, Bundle savedInstanceState) {
        setAdapter(mCurrentAdapterIndex);
        super.onViewCreated(view, savedInstanceState);
    }

    @Override
    public void onDetach() {
        XqLog.d("ImageListViewFragment.onDetach");
        super.onDetach();
    }

    @Override
    public void onDestroy() {
        XqLog.d("ImageListViewFragment.onDestroy");
        if (mCurrentAdapter != null) {
            mCurrentAdapter.shutDown();
            mCurrentAdapter = null;
            System.gc();
        }
        super.onDestroy();
    }

    @Override
    public void onDestroyView() {
        XqLog.d("ImageListViewFragment.onDestroyView");
        super.onDestroyView();
    }

    @Override
    public void onStop() {
        XqLog.d("ImageListViewFragment.onStop");
        super.onStop();
    }

    @Override
    public void onPause() {
        XqLog.d("ImageListViewFragment.onPause");
        super.onPause();
    }

    @Override
    public void onResume() {
        XqLog.d("ImageListViewFragment.onResume");
        super.onResume();
    }

    /**
     *
     * @param index
     */
    private void setAdapter(int index){
        if (mCurrentAdapter != null) {
            mCurrentAdapter.shutDown();
            mCurrentAdapter = null;
            System.gc();
        }

        mCurrentAdapterIndex = index;
        mPerfListener = new PerfListener();
        switch (index) {
            case Constants.FRESCO_INDEX:
                mCurrentAdapter = new FrescoListViewAdapter(getContext(),imgList, ConfigConstants.getImagePipelineConfig(getContext()),mPerfListener);
                break;
            case Constants.FRESCO_OKHTTP_INDEX:
                mCurrentAdapter = new FrescoListViewAdapter(getContext(),imgList,  ImagePipelineConfigFactory.getOkHttpImagePipelineConfig(getContext()),mPerfListener);
                break;
            default:
                mCurrentAdapter = null;
                break;
        }

        listView.setAdapter(mCurrentAdapter);
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> adapterView, View view, final int i, long l) {

/*                //直接用AlertDialog对话框，不建议使用
                AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
                // Get the layout inflater
                LayoutInflater inflater = getActivity().getLayoutInflater();
                View dialogview = inflater.inflate(R.layout.fragment_edit_name, null);
                // Inflate and set the layout for the dialog
                // Pass null as the parent view because its going in the dialog layout
                builder.setView(dialogview)
                        // Add action buttons
                        .setPositiveButton("Sign in",
                                new DialogInterface.OnClickListener()
                                {
                                    @Override
                                    public void onClick(DialogInterface dialog, int id)
                                    {
                                    }
                                })
                        .setNegativeButton("Cancel", null)
                        .create()
                        .show();*/


                final String reqStr = imgList[i];

/*                ImagePipeline imagePipeline = Fresco.getImagePipeline();
                ImageRequest imageRequest = ImageRequestBuilder.newBuilderWithSource(Uri.parse(reqStr))
                        .build();
                DataSource<CloseableReference<CloseableImage>> dataSource = imagePipeline.fetchDecodedImage(imageRequest,getContext());

                //这个直接获取原图Bitmap
                dataSource.subscribe(new BaseBitmapDataSubscriber() {
                    @Override
                    protected void onNewResultImpl( Bitmap bitmap) {
                        Bitmap bmp = bitmap;
                        int w = bitmap.getWidth();
                        int h = bitmap.getHeight();
                        try {
                            FileOutputStream fos = new FileOutputStream(FileUtils.getSDPath() + "ceshi"+i+".png");
                            bmp.compress(Bitmap.CompressFormat.PNG,100,fos);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }


                    }

                    @Override
                    protected void onFailureImpl(DataSource<CloseableReference<CloseableImage>> dataSource) {

                    }
                }, Executors.newFixedThreadPool(5));*/


                File file = FrescoUtils.getCachedImageOnDisk(Uri.parse(reqStr),getActivity());
                Uri picUri = null;
                if(file != null){
                    picUri = Uri.parse(FrescoUtils.getUriPathFromPath(getContext(),FrescoUtils.LOCAL_FILE_SCHEME_INT,file.getAbsolutePath()));
                }else{
                    picUri = Uri.parse(reqStr);
                }
                XqLog.d("picUri=>"+picUri.toString());
                XqLog.d("picUri.getPath=>"+picUri.getPath());
                XqLog.d("picUri.getScheme=>"+picUri.getScheme());
                XqLog.d("picUri.getHost=>"+picUri.getHost());
                XqLog.d("type=>"+FrescoUtils.getTypeImageSequence(picUri));
                ImageMessageDialogFragment imageMessageDialogFragment = ImageMessageDialogFragment.newInstance(picUri);
                imageMessageDialogFragment.setStyle(DialogFragment.STYLE_NORMAL,R.style.fullscreendialog);  //设置对话框的弹出主题，包括全屏无标题栏，以及出现和消失的动画
                imageMessageDialogFragment.show(getFragmentManager(), ImageMessageDialogFragment.class.getSimpleName());
                return false;
            }
        });
        if(mCurrentAdapter !=null){
            mCurrentAdapter.notifyDataSetChanged();
        }
    }
    @Override
    public boolean onBackPressed() {
        return false;
    }

    @Override
    public void onUpdateFragment(Bundle bundle) {
        if(bundle != null){
            int position = bundle.getInt(Constants.LOADER_INDEX);
            setAdapter(position);
        }
        super.onUpdateFragment(bundle);
    }
}
